// client.js - Web client for communicating with backend APIs

class APIClient {
    constructor(baseURL = '') {
        this.baseURL = baseURL;
    }

    // Generic request method
    async request(endpoint, options = {}) {
        const url = `${this.baseURL}${endpoint}`;
        const config = {
            headers: {
                'Content-Type': 'application/json',
                ...options.headers
            },
            ...options
        };

        try {
            const response = await fetch(url, config);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return await response.json();
        } catch (error) {
            console.error(`Error fetching ${url}:`, error);
            throw error;
        }
    }

    // Get stock features data
    async getFeatures(instruments, fields, startTime, endTime) {
        return this.request('/api/qlib-data/features', {
            method: 'POST',
            body: JSON.stringify({
                instruments,
                fields,
                start_time: startTime,
                end_time: endTime
            })
        });
    }

    // Get instrument list
    async getInstruments(market = 'csi300', startTime = '2020-01-01', endTime = '2023-12-31') {
        const params = new URLSearchParams({
            market,
            start_time: startTime,
            end_time: endTime
        });
        return this.request(`/api/qlib-data/instruments?${params}`);
    }

    // Get calendar data
    async getCalendar(startTime = '2020-01-01', endTime = '2023-12-31', freq = 'day') {
        const params = new URLSearchParams({
            start_time: startTime,
            end_time: endTime,
            freq
        });
        return this.request(`/api/qlib-data/calendar?${params}`);
    }

    // Get latest stock data
    async getLatestData(market = 'csi300', limit = 20) {
        const params = new URLSearchParams({
            market,
            limit
        });
        return this.request(`/api/qlib-data/latest-data?${params}`);
    }

    // Custom stock fields
    async getCustomFields(instruments = [], customFields = [], startTime, endTime) {
        return this.request('/api/custom-fields', {
            method: 'POST',
            body: JSON.stringify({
                instruments,
                custom_fields: customFields,
                start_time: startTime,
                end_time: endTime
            })
        });
    }

    // Strategy edit submission
    async submitStrategyEdit(strategyId, strategyData) {
        return this.request('/api/strategy/edit', {
            method: 'POST',
            body: JSON.stringify({
                strategy_id: strategyId,
                strategy_data: strategyData
            })
        });
    }

    // Execute strategy
    async executeStrategy(strategyId, parameters = {}) {
        return this.request('/api/strategy/execute', {
            method: 'POST',
            body: JSON.stringify({
                strategy_id: strategyId,
                parameters
            })
        });
    }

    // Get strategy performance
    async getStrategyPerformance(strategyId, startTime, endTime) {
        return this.request('/api/strategy/performance', {
            method: 'POST',
            body: JSON.stringify({
                strategy_id: strategyId,
                start_time: startTime,
                end_time: endTime
            })
        });
    }

    // Get strategy details
    async getStrategyDetails(strategyId) {
        return this.request('/api/strategy/details', {
            method: 'POST',
            body: JSON.stringify({
                strategy_id: strategyId
            })
        });
    }

    // Submit trading request
    async submitTradingRequest(stockCode, tradeType, price, quantity, accountId) {
        return this.request('/api/trading/submit', {
            method: 'POST',
            body: JSON.stringify({
                stock_code: stockCode,
                trade_type: tradeType,
                price,
                quantity,
                account_id: accountId
            })
        });
    }

    // Get portfolio data
    async getPortfolioData(accountId) {
        return this.request('/api/portfolio/data', {
            method: 'POST',
            body: JSON.stringify({
                account_id: accountId
            })
        });
    }
}

// Create a global instance of the API client
const apiClient = new APIClient();

// Export for use in other modules
if (typeof module !== 'undefined' && module.exports) {
    module.exports = { APIClient, apiClient };
}